﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using Gadgeteer.Modules.Community;
using System.IO;
using System.Drawing;

namespace Gadgeteer.Modules.Community.XBee.InteractiveConsole
{
    class Program
    {
        private static XBeeClient xbeeClient;

        static void Main(string[] args)
        {
            bool initialized = false;

            while (!initialized)
            {
                Console.WriteLine("Enter the COM port your XBee dongle is on.");
                string userEnteredCOMPort = Console.ReadLine();
                int comPort;
                while (!Int32.TryParse(userEnteredCOMPort, out comPort))
                {
                    Console.WriteLine("Invalid format, enter a number.");
                    userEnteredCOMPort = Console.ReadLine();
                }

                try
                {
                    xbeeClient = new XBeeClient(comPort);
                    initialized = true;
                }
                catch (IOException ioException)
                {
                    Console.WriteLine("Invalid COM Port: " + ioException.ToString());
                }
            }
            
            xbeeClient.RecordBytesReceivedHistory = true;
            xbeeClient.TestCompleted += new TestCompletedEventHandler(client1_TestCompleted);
            xbeeClient.StringReceived += new StringReceivedEventHandler(xbeeClient_StringReceived);
            xbeeClient.PictureReceived += new PictureReceivedEventHandler(xbeeClient_PictureReceived);

            Console.WriteLine("Enter 'history' to print the raw bytes received history to debug window");
            Console.WriteLine("Enter 'test' to run the functional test Suite'");
            Console.WriteLine("Enter 'send {your message}' to broadcast send a message, for example, 'send hello world!'");

            string message = string.Empty;
            while ((message = Console.ReadLine().ToLower()) != "exit")
            {
                int indexOfFirstSpace = message.IndexOf(' ');
                string command = indexOfFirstSpace > 0 ? message.Substring(0, indexOfFirstSpace) : message;
                switch (command)
                {
                    case "history":
                        Console.WriteLine("Printing bytes received history to debug window");
                        xbeeClient.PrintBytesReceivedHistory();
                        break;
                    case "test":
                        Console.WriteLine("Running Functional Tests...");
                        PrintTestResults(xbeeClient.RunFunctionalTests(1));
                        break;
                    case "send":
                        if (message.Length <= indexOfFirstSpace)
                        {
                            Console.WriteLine("invalid argument, send command must have some text to send");
                            continue;
                        }
                        string payload = message.Substring(indexOfFirstSpace);
                        xbeeClient.UploadStringAsync(payload);
                        break;
                    default:
                        Console.WriteLine("I don't know how to " + command);
                        break;
                }

            }

        }

        static void xbeeClient_PictureReceived(object sender, PictureReceivedEventArgs e)
        {
            Console.WriteLine("Picture received, " + e.Data.Length + " total bytes.");
            using (MemoryStream ms = new MemoryStream(e.Data, false))
            {
                Bitmap bmp = new Bitmap(ms);
                string fileName = "receivedImage.bmp";
                bmp.Save(fileName);
                Console.WriteLine(fileName);
            }
        }

        static void xbeeClient_StringReceived(object sender, StringReceivedEventArgs e)
        {
            Console.WriteLine("received string");
            Console.WriteLine(e.Message);
        }

        static void client1_TestCompleted(object sender, TestCompletedEventArgs e)
        {
            Console.WriteLine("testCompleted: " + e.Test.ToString());
        }

        private static void PrintTestResults(BaseTest[] tests)
        {
            for (int i = 0; i < tests.Length; i++)
            {
                Console.WriteLine(tests[i].ToString());
            }
        }

    }
}
